package top.techqi.app.mcs51.usbdlk.vm

import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import top.techqi.app.mcs51.const.ACTION_USB_PERMISSION
import top.techqi.app.mcs51.const.EXTRA_PENDING_INTF_ID
import top.techqi.core.App

class UsbdlkViewModel : ViewModel() {
    private val usbManager = App.INSTANCE.getSystemService(Context.USB_SERVICE) as UsbManager

    val devicesData = MutableLiveData<List<UsbDevice>>()
    val devicesOpen = MutableLiveData<List<Pair<UsbDevice, Int>>>(emptyList())

    val deviceAwait = MutableLiveData<Pair<UsbDevice, Int>>()

    fun scanDevices() {
        viewModelScope.launch {
            val devices: List<UsbDevice> = usbManager.deviceList.values
                .sortedBy { it.deviceName }

            devicesData.postValue(devices)
        }
    }

    fun hasPermission(device: UsbDevice): Boolean {
        return usbManager.hasPermission(device)
    }

    fun reqPermission(device: UsbDevice, intfId: Int) {
        val intent = Intent(ACTION_USB_PERMISSION)
        intent.putExtra(EXTRA_PENDING_INTF_ID, intfId)
        val pi = PendingIntent.getBroadcast(
            App.INSTANCE, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT
        )
        usbManager.requestPermission(device, pi)
    }

    fun openDevice(device: UsbDevice, intfId: Int) {
        val list = ArrayList(devicesOpen.value ?: emptyList())
        val pair = Pair(device, intfId)
        if (!list.contains(pair)) {
            list.add(Pair(device, intfId))
            devicesOpen.postValue(list)
        }
        deviceAwait.postValue(pair)
    }

    fun closeDevice(device: UsbDevice, intfId: Int) {
        val list = ArrayList(devicesOpen.value ?: emptyList())
        val pair = Pair(device, intfId)
        if (list.remove(pair)) {
            devicesOpen.postValue(list)
        }
    }
}
